import FreeCAD
import Import
import os
import io
import shutil
import time
#import pyrender
from .viewObject import ViewObject
from .gltf import Gltf
from .tuoVisual import TuoVisual
#from .renderer import *

class Document:
    def __init__(self, name):
        self.doc = FreeCAD.newDocument(name)
        FreeCAD.ActiveDocument = self.doc
        self.colorInfos = None
        self.viewObjects = []
        self.r_mesh = None
        self.replace = None
    def cleanObjects(self):
        #for obj in self.doc.Objects:
        #    self.doc.removeObject(obj.Name)
        #self.colorInfos = None
        #self.viewObjects = []
        #self.r_mesh = None
        while len(self.doc.Objects) > 0:
            self.doc.removeObject(self.doc.Objects[0].Name)
        self.colorInfos = None
        self.viewObjects = []
        self.r_mesh = None
        self.replace = None

    def setColorInfos(self, infos):
        if(infos and len(infos) > 0):
            self.colorInfos = {}
            for info in infos:
                self.colorInfos[info[0].Name] = info[1]

    def visualize(self):
        # objectInfo:
        # {
        #   maxVolume,
        #   shapeNum
        # }
        #self.scene_min = None
        #self.scene_max = None
        print('visualizing')

        self.objectInfo = {'shapeNum':0, 'maxVolume': 0, 'scene_min': None, 'scene_max': None\
,'verticesNum':0}
        currentOrder = 0

        print('length of doc:', len(self.doc.RootObjects))
        for obj in self.doc.RootObjects:
            viewObj = ViewObject(obj, self.colorInfos, info = self.objectInfo, currentOrder = currentOrder)
            self.viewObjects.append(viewObj)
            currentOrder += 1


        for obj in self.viewObjects:
            obj.parse(self.objectInfo)
        print('objectInfo:', self.objectInfo)


    def getTuoVisualObject(self, name):
        if(len(self.viewObjects)) == 0:
            self.visualize()
        #print('before merged:', self.objectInfo)
        #toProcess = []
        #rootShape = []
        #for obj in self.viewObjects:
        #    if(len(obj.children) == 0):
        #        rootShape.append(obj)
        #    else:
        #        toProcess.append(obj)
        #toProcess.append(ViewObject(rootShape))
        #
        #self.objectInfo['mergedNum'] = 0
        #for obj in toProcess:
        #    obj.mergeShapes(info = self.objectInfo)

        #print('after merged:', self.objectInfo)
        #return TuoVisual(toProcess, name, self.objectInfo, self.replace)
        return TuoVisual(self.viewObjects, name, self.objectInfo, self.replace)

    def exportTuoVisual(self, filename):
        path, basename = os.path.split(filename)
        name = os.path.splitext(basename)[0]


        tv = self.getTuoVisualObject(name)


        for (name, blob ) in tv.data.blobs.items():
            with open(path +'/' + name, 'wb') as fd:
                blob.seek(0)
                shutil.copyfileobj(blob, fd)
                blob.seek(0)
        with open(path + '/' + basename + '.TuoVisual', 'w') as fd:
            shutil.copyfileobj(tv.tuoVisual, fd)
            tv.tuoVisual.seek(0)

#    def constructPrimitives(self):
#        if len(self.viewObjects) == 0:
#            self.visualize()
#        primitives = []
#        for viewObject in self.viewObjects:
#            primitives.extend(viewObject.renderPrimitive())
        #self.r_mesh = pyrender.Mesh(primitives)

#    def renderImage(self):
#        if self.r_mesh == None:
#            self.constructPrimitives()
#        img = renderMesh(self.r_mesh)
#        return img

#    def renderImageFile(self, filename):
#        '''
#        filename: fullpath of filename
#        '''
#        blob = self.renderImage()
#        with open(filename, 'wb') as fd:
#            blob.seek(0)
#            shutil.copyfileobj(blob, fd)
#            blob.seek(0)

#    def renderVideo(self):
#        if self.r_mesh == None:
#            self.constructPrimitives()
#        video = renderMeshAnimation(self.r_mesh)
#        return video

#    def renderVideoFile(self, filename):
#        blob = self.renderVideo()
#        with open(filename, 'wb') as fd:
#            blob.seek(0)
#            shutil.copyfileobj(blob, fd)
#            blob.seek(0)

aDoc = Document('cadparser')

